<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="baTable.form.operate ? true : false"
    @close="baTable.toggleForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ baTable.form.operate !== "edit" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar
      v-loading="baTable.form.loading"
      class="ba-table-form-scrollbar"
    >
      <div
        class="ba-operate-form"
        :class="'ba-' + baTable.form.operate + '-form'"
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="baTable.onSubmit(formRef)"
          :model="baTable.form.items"
          label-position="right"
          :label-width="baTable.form.labelWidth + 'px'"
          :rules="rules"
          v-if="!baTable.form.loading"
        >
          <el-form-item label="产品编码">
            <el-input
              v-model="baTable.form.items!.productCode"
              placeholder="请选择下方产品物料区获取编码"
            />
            <el-scrollbar
              ref="verticalMenusRef"
              class="vertical-menus-scrollbar"
              style="border: 1px solid #dcdfe6; width: 100%"
            >
              <el-input
                class="filterInput"
                v-model="filterText"
                placeholder="关键词过滤"
              />

              <el-tree
                ref="treeRef"
                class="filter-tree"
                :data="state.bomOptions"
                :props="{ label: 'name', value: 'id' }"
                node-key="code"
                show-checkbox
                :default-checked-keys="
                  baTable.form.operate == 'edit'
                    ? [baTable.form.items.productCode]
                    : []
                "
                :filter-node-method="filterNode"
                @check="rightClick"
              />
            </el-scrollbar>
          </el-form-item>
          <el-form-item label="工作中心/车间信息" prop="workshopCode">
            <el-scrollbar
              ref="verticalMenusRef"
              class="vertical-menus-scrollbar"
              style="border: 1px solid #dcdfe6; width: 100%"
            >
              <el-tree
                ref="treeRef2"
                :default-checked-keys="
                  baTable.form.operate == 'edit'
                    ? [baTable.form.items.workshopId]
                    : baTable.form.operate == 'add'
                    ? [baTable.form.items.workshopId]
                    : []
                "
                class="tree-border"
                :data="state.stationOptions"
                :props="{
                  children: 'children',
                  label: 'deptName',
                  value: 'id',
                }"
                node-key="deptId"
                show-checkbox
                @check="handleCheckChange"
                :filter-node-method="filterNodeStation"
              />
            </el-scrollbar>
          </el-form-item>
          <el-form-item label="优先级" prop="priority">
            <el-select
              v-model="baTable.form.items!.priority"
              placeholder="请选择优先级"
              @change="priorityChange"
            >
              <el-option
                v-for="item in state.priorityOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue - 0"
                :disabled="item.status == 1"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="生产类型" prop="productType">
            <el-select
              v-model="baTable.form.items!.productType"
              placeholder="请选择生产类型"
            >
              <el-option
                v-for="item in state.productTypeOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue - 0"
                :disabled="item.status == 1"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="计划状态" prop="planState">
            <el-select
              v-model="baTable.form.items!.planState"
              placeholder="请选择计划状态"
            >
              <el-option
                v-for="item in state.planStateOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue - 0"
                :disabled="item.status == 1"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否暂停" prop="isSuspend">
            <el-radio-group v-model="baTable.form.items!.isSuspend">
              <el-radio
                v-for="(item, index) in state.isSuspendDict"
                :key="index"
                :label="item.dictValue - 0"
                border
                >{{ item.dictLabel }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否排产" prop="isProduct">
            <el-radio-group v-model="baTable.form.items!.isProduct">
              <el-radio
                v-for="(item, index) in state.isProductDict"
                :key="index"
                :label="item.dictValue - 0"
                border
                >{{ item.dictLabel }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="物料准备状态" prop="materialState">
            <el-select
              v-model="baTable.form.items!.materialState"
              placeholder="请选择物料准备状态"
            >
              <el-option
                v-for="item in state.materialOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
                :disabled="item.status == 1"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工装准备状态" prop="toolState">
            <el-select
              v-model="baTable.form.items!.toolState"
              placeholder="请选择工装准备状态"
            >
              <el-option
                v-for="item in state.toolOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
                :disabled="item.status == 1"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="产品名称" prop="productName">
            <el-input
              v-model="baTable.form.items!.productName"
              placeholder="请输入产品名称"
            />
          </el-form-item> -->
          <el-form-item label="计划数" prop="planQuantity">
            <el-input-number
              v-model="baTable.form.items!.planQuantity"
              controls-position="right"
              :min="0"
            />
          </el-form-item>
          <el-form-item label="投产数" prop="productQuantity">
            <el-input-number
              v-model="baTable.form.items!.productQuantity"
              controls-position="right"
              :min="0"
            />
          </el-form-item>
          <el-form-item label="选择时间" prop="endTime">
            <el-date-picker
              v-model="state.doTime"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="截止时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="getValue"
            />
          </el-form-item>
          <el-form-item label="交付日期" prop="deliverDate">
            <el-date-picker
              v-model="baTable.form.items!.deliverDate"
              type="date"
              placeholder="请选择交付日期"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD "
            />
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'"
      >
        <el-button @click="baTable.toggleForm('')">取消</el-button>
        <el-button
          v-blur
          :loading="baTable.form.submitLoading"
          @click="baTable.onSubmit(formRef)"
          type="primary"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import {
  ref,
  reactive,
  onMounted,
  onBeforeUnmount,
  inject,
  computed,
  watch,
  nextTick,
} from "vue";
import type baTableClass from "@/utils/baTable";
import FormItem from "@/components/formItem/index.vue";
import type { ElForm, FormItemRule, FormRules, ElTree } from "element-plus";
import { useConfig } from "@/store/config"; //后台布局相关仓库
import { getDictData } from "@/utils/common";

//接受来自父组件的注入
const baTable = inject("baTable") as baTableClass;
const dictionary = inject("dictionary") as any;
const bom = inject("bom") as any;
const bomD = inject("bomD") as any;
const config = useConfig();
const station = inject("station") as any;
const plan = inject("plan") as any;
const dept = inject("dept") as any;
const formRef = ref<InstanceType<typeof ElForm>>();

const state: {
  bomOptions: anyObj[];
  doTime: any[];
  stationOptions: anyObj[];
  toolOptions: anyObj[];
  materialOptions: anyObj[];
  priorityOptions: anyObj[];
  productTypeOptions: anyObj[];
  planStateOptions: anyObj[];
  isSuspendDict: anyObj[];
  isProductDict: anyObj[];
} = reactive({
  doTime: [],
  bomOptions: [],
  stationOptions: [],
  toolOptions: [],
  materialOptions: [],
  priorityOptions: [],
  productTypeOptions: [],
  planStateOptions: [],
  isSuspendDict: [],
  isProductDict: [],
});

const treeRef = ref<InstanceType<typeof ElTree>>();
const treeRef2 = ref<InstanceType<typeof ElTree>>();

//物料筛选
const filterText = ref(""); //产品编码关键词过滤
const filterNode = (value: string, data: any) => {
  console.log("产品编码过滤", value, data);
  if (!value) return true;
  return data.name.includes(value);
};

// 车间关键词过滤
const filterNodeStation = (value: string, data: any) => {
  if (!value) return true;
  return data.name.includes(value);
};

// 选择产品编码的动作
const rightClick = (MouseEvent: any, object: any, Node: any, element: any) => {
  console.log("产品编码选择的数据", MouseEvent, object, Node, element);
  if (object.checkedKeys.length) {
    //有数据
    baTable.form.items!.productCode = MouseEvent.code;
    baTable.form.items!.productName = MouseEvent.name;
    baTable.form.items!.materialType = MouseEvent.type;
    getStationInfo(MouseEvent);
  } else {
    //无数据
    baTable.form.items!.productCode = "";
    baTable.form.items!.productName = "";
    baTable.form.items!.materialType = "";
  }
};

//获取车间信息
const getStationInfo = (row: any) => {
  bomD
    .getBomDictInfo({ name: row.name, code: row.code })
    .then((res: any) => {
      baTable.form.items!.workshopCode = res[0].workshopCode;
      baTable.form.items!.workshopName = res[0].workshopName;
    })
    .catch((err: any) => {});
};

//选择车间
const handleCheckChange = (row: any, node: any) => {
  console.log("row", row, "node", node);
  if (node.checkedKeys.length == 0) {
    baTable.form.items!.workshopCode = "";
    baTable.form.items!.workshopName = "";
  } else {
    baTable.form.items!.workshopCode = row.deptId;
    baTable.form.items!.workshopName = row.deptName;
  }
};

const rules = reactive<FormRules>({
  productCode: [
    { required: true, message: "产品编码不能为空", trigger: "blur" },
  ],
  productName: [
    { required: true, message: "产品名称不能为空", trigger: "blur" },
  ],
  planQuantity: [
    { required: true, message: "计划数不能为空", trigger: "blur" },
  ],
  productQuantity: [
    { required: true, message: "投产数不能为空", trigger: "blur" },
  ],
  deliverDate: [
    { required: true, message: "交付日期不能为空", trigger: "blur" },
  ],
  endTime: [{ required: true, message: "选择时间不能为空", trigger: "blur" }],
  // priority: [{ required: true, message: "优先级不能为空", trigger: "blur" }],
});

//针对侧边栏菜单高度让滚动条自适应
const overviewMenusScrollbarHeight = computed(() => {
  // 加上了50px的头部距离
  let menuTopBarHeight = 50;
  if (config.layout.layoutMode == "Default") {
    //32为aside上下margin
    return "calc(100vh - " + (172 + menuTopBarHeight) + "px)";
  } else {
    return "calc(100vh - " + (140 + menuTopBarHeight) + "px)";
  }
});

//选择时间
const getValue = (value: any) => {
  console.log("选择时间", value);
  if (value) {
    baTable.form.items!.startTime = value[0];
    baTable.form.items!.endTime = value[1];
  } else {
    baTable.form.items!.startTime = "";
    baTable.form.items!.endTime = "";
  }
  // baTable.comSearch.form = Object.assign(
  //   baTable.comSearch.form,
  //   value
  //     ? {
  //         startTime: value[0],
  //         endTime: value[1],
  //       }
  //     : { startTime: "", endTime: "" }
  // );
};
const priorityChange = (e: any) => {
  console.log("e", e);
};
//获取字典
const getMenuStatus = () => {
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["toolState"])
  ) {
    dictionary.getDictInfo("sys_plan_toolstate").then((res: any) => {
      dictionary.moreTags["toolState"] = getDictData(res);
      plan.options["toolState"] = res;
      state.toolOptions = res;
      console.log("获取工装准备状态的字典", dictionary.moreTags);
    });
  } else {
    state.toolOptions = plan.options["toolState"];
  }
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["materialState"])
  ) {
    dictionary.getDictInfo("sys_plan_materialstate").then((res: any) => {
      dictionary.moreTags["materialState"] = getDictData(res);
      plan.options["materialState"] = res;
      state.materialOptions = res;
      console.log("获取物料准备状态的字典", dictionary.moreTags);
    });
  } else {
    state.materialOptions = plan.options["materialState"];
  }

  state.priorityOptions = plan.options["priority"];
  console.log("优先级", state.priorityOptions);

  state.isSuspendDict = plan.options["isSuspend"];
  state.planStateOptions = plan.options["planState"];
  state.isProductDict = plan.options["isProduct"];
  state.productTypeOptions = plan.options["productType"];
};

onMounted(() => {
  getMenuStatus();
  //获取物料数据
  bom.getBomUniqeByRole().then((res: any) => {
    state.bomOptions = res;
    console.log("bomOptions", res);
  });
  //获取工作中心数据
  dept.getDeptOrigin().then((res: any) => {
    state.stationOptions = res;
    console.log("stationOptions", res);
  });
  setTimeout(() => {
    state.doTime[0] = baTable.form.items!.startTime;
    state.doTime[1] = baTable.form.items!.endTime;
  }, 500);
});
watch(filterText, (val) => {
  treeRef.value!.filter(val);
});
</script>
<style scoped lang="scss">
.filter-tree {
  height: 200px;
}
.el-scrollbar {
  overflow: auto;
  position: relative;
  height: 100%;

  .el-scrollbar__wrap {
    overflow: auto;
    height: 100%;
  }
}

.vertical-menus-scrollbar {
  height: v-bind(overviewMenusScrollbarHeight);
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
